package com.zhang.IO.BIO;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOtest {

    public static void main(String[] arg0) throws IOException {

        //创建线程池
        ExecutorService newCachedThreadPool= Executors.newCachedThreadPool();
        //创建客户端
        ServerSocket serverSocket=new ServerSocket(666);
        System.out.println("服务端启动");
        while (true)
        {
            System.out.println("线程ID："+Thread.currentThread().getId()+"线程名字："+Thread.currentThread().getName());

            //拿到监听的Socket
            System.out.println("等待连接。。。");
            //todo  在此阻塞
            final Socket socket= serverSocket.accept();
            System.out.println("连接上了一个客户端");

            //开启一个线程处理获取到的socket
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);

                }
            });

        }

    }

    /**
     * 编写一个handler方法和客户端通讯
     * @param socket
     */
    public static void handler(Socket socket)
    {

        try {
            System.out.println("线程ID："+Thread.currentThread().getId()+"线程名字："+Thread.currentThread().getName());
            byte[] bytes=new byte[1024];
            //获取客户端消息流
            InputStream inputStream=socket.getInputStream();
            while (true) {
                System.out.println("线程ID："+Thread.currentThread().getId()+"线程名字："+Thread.currentThread().getName());
                //循环读取客户端数据
                //todo  在此阻塞
                System.out.println("read。。。");
               int read = inputStream.read(bytes);
               if (read != -1) {
//                  输出数据
                   System.out.println(new String(bytes,0,read));
               }else {
                  break;
               }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            System.out.println("关闭和客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
